<script lang="ts" setup>
import { getPatientConsultOrderListAPI } from '@/apis/consult'
import { deletePatientOrderByIdAPI, putPatientOrderCancelByIdAPI } from '@/apis/order';
import {
  OrderStatus,
  type ConsultOrderItem,
  type GetPatientConsultOrderListParams,
} from '@/types/consult'
import { ref } from 'vue'

// 接收父组件传递的参数
const props = defineProps<{
  type: number
}>()
// 定义查询参数
const query = ref<Required<GetPatientConsultOrderListParams>>({
  type: props.type, // 问诊类型
  current: 1, // 页码
  pageSize: 10, // 页大小
})

// 获取订单列表
const list = ref<ConsultOrderItem[]>([])
// 总条数
const total = ref(0)
//总页数
const pageTotal = ref(0)
// 是否加载中
const loadMoreStatus = ref<UniHelper.UniLoadMoreStatus>('loading')
// 获取订单列表
const getList = async (isMore = false) => {
  // 加载状态 - 加载中
  loadMoreStatus.value = 'loading'
  // 发送请求
  const res = await getPatientConsultOrderListAPI(query.value)
  // console.log(res)
  // 加载状态 - 请求完成
  if (isMore) {
    list.value.push(...res.data.rows)
  } else {
    list.value = res.data.rows // 订单列表
  }
  total.value = res.data.total // 总条数
  pageTotal.value = res.data.pageTotal // 总页数
  // 判断是否还有更多数据
  if (query.value.current < pageTotal.value) {
    loadMoreStatus.value = 'more'
  } else {
    loadMoreStatus.value = 'noMore'
  }
}
// 加载更多数据
const getMoreData = async () => {
  // 如果当前页已经是最后一页，则不再加载
  if (query.value.current >= pageTotal.value) return
  // 页码加1
  query.value.current++
  // 加载更多数据
  await getList(true)
}
// 初始加载
getList()
// 下拉刷新状态
const refresherTriggered = ref(false)
// 下拉刷新事件
const onRefresh = async () => {
  // 开启下拉刷新状态
  refresherTriggered.value = true
  // 重置页码
  query.value.current = 1
  // 重新加载数据
  await getList()
  // 关闭下拉刷新状态
  refresherTriggered.value = false
}
// 是否显示查看更多
const activeShowMoreId = ref('')
// / 删除订单
const handleDeleteOrder = (item: ConsultOrderItem) => {
  // 弹窗提示
  uni.showModal({
    title: '提示',
    content: '确定删除订单吗？',
    confirmColor: '#16c2a3',
    success: async (res) => {
      if (res.confirm) {
        // 后端：调用删除订单接口
        await deletePatientOrderByIdAPI(item.id)
        // 提示
        uni.showToast({ title: '删除订单成功', icon: 'success' })
        // 前端：删除订单项（注意：这里循环项 item 命名可能冲突）
        list.value = list.value.filter((v) => v.id !== item.id)
      }
    },
  })
}
// 取消订单
const handleCancelOrder = (item: ConsultOrderItem) => {
  // 弹窗提示
  uni.showModal({
    title: '提示',
    content: '确定取消订单吗？',
    confirmColor: '#16c2a3',
    success: async (res) => {
      if (res.confirm) {
        // 调用取消订单接口
        await putPatientOrderCancelByIdAPI(item.id)
        // 提示
        uni.showToast({ title: '取消订单成功', icon: 'success' })
        // 修改订单状态
        item.status = OrderStatus.YiQuXiao
        item.statusValue = '已取消'
      }
    },
  })
}
// 问诊记录，继续咨询
const handleGoToConsultRoom = (item: ConsultOrderItem) => {
  uni.navigateTo({ url: `/subpkg_consult/pages/room/room?orderId=${item.id}` })
}
</script>

<template>
  <scroll-view
    refresher-enabled
    :refresher-triggered="refresherTriggered"
    @refresherrefresh="onRefresh"
    refresher-background="#f6f6f6"
    class="uni-scroll-view"
    scroll-y
    @click="activeShowMoreId = ''"
    @scrolltolower="getMoreData"
  >
    <view class="consult-list">
      <view class="consult-list-item" v-for="item in list" :key="item.id">
        <view class="consult-header">
          <view class="label">
            <image class="doctor-avatar" src="/static/uploads/doctor-avatar.jpg" />
            <text>{{ item.typeValue }}（自动分配医生）</text>
          </view>
          <!-- 多个条件判断可以用 includes 化简  -->
          <text
            class="status"
            :class="{
              'color-1': item.status === OrderStatus.DaiZhiFu,
              'color-2': [OrderStatus.DaiJieZhen, OrderStatus.ZiXunZhong].includes(item.status),
              'color-3': [OrderStatus.YiWanCheng, OrderStatus.YiQuXiao].includes(item.status),
            }"
          >
            {{ item.statusValue }}
          </text>
        </view>
        <navigator 
        class="consult-body" 
        hover-class="none" 
        :url="`/subpkg_consult/pages/order_detail/order_detail?id=${item.id}`">
          <uni-list :border="false">
            <uni-list-item :border="false" title="病情描述" :right-text="item.illnessDesc" />
            <uni-list-item :border="false" title="价格" :right-text="`¥ ${item.payment}`" />
            <uni-list-item :border="false" title="创建时间" :right-text="item.createTime" />
          </uni-list>
        </navigator>
        <view class="consult-footer">
          <view class="uni-button more" v-if="item.status === OrderStatus.YiWanCheng">
            <text
              class="label"
              @click.stop="activeShowMoreId = activeShowMoreId === item.id ? '' : item.id"
              >更多</text
            >
            <uni-transition :show="activeShowMoreId === item.id">
              <view class="list">
                <view class="list-item">查看处方</view>
                <view class="list-item" @click="handleDeleteOrder(item)">删除订单</view>
              </view>
            </uni-transition>
          </view>
          <template v-if="item.status === OrderStatus.DaiZhiFu">
            <button class="uni-button minor" @click="handleCancelOrder(item)">取消订单</button>
            <button class="uni-button">去支付</button>
          </template>

          <template v-if="item.status === OrderStatus.DaiJieZhen">
            <button class="uni-button minor" @click="handleCancelOrder(item)">取消订单</button>
            <button @click="handleGoToConsultRoom(item)" class="uni-button">继续咨询</button>
          </template>

          <template v-if="item.status === OrderStatus.ZiXunZhong">
            <button @click="handleGoToConsultRoom(item)" class="uni-button" >继续咨询</button>
          </template>

          <template v-if="item.status === OrderStatus.YiWanCheng">
            <button class="uni-button minor" @click="handleGoToConsultRoom(item)">问诊记录</button>
            <button v-if="item.evaluateId" class="uni-button minor">查看评价</button>
            <button v-else class="uni-button">去评价</button>
          </template>

          <template v-if="item.status === OrderStatus.YiQuXiao">
            <button class="uni-button minor" @click="handleDeleteOrder(item)">删除订单</button>
            <button class="uni-button">咨询其它医生</button>
          </template>
        </view>
      </view>
      <!-- 加载状态 -->
      <uni-load-more
        :status="loadMoreStatus"
        color="#C3C3C5"
        :icon-size="16"
        :content-text="{
          contentdown: '上拉显示更多',
          contentrefresh: '数据正在加载中',
          contentnomore: '没有更多数据了',
        }"
      />
    </view>
  </scroll-view>
</template>

<style lang="scss">
@import './styles.scss';
</style>
